const requestHelper = require('../../utils/request');
const buildUrl = requestHelper.buildUrl || ((url) => url);

Page({
  data: {
    cid: null,
    orderId: null,
    messages: [],
    draft: '',
    currentUserId: null
  },

  onLoad(options) {
    const cid = Number(options.cid || 0);
    const orderId = options.orderId || '';
    if (!cid) {
      wx.showToast({ title: '会话不存在', icon: 'none' });
      return;
    }
    const app = getApp();
    const userId = app.globalData && app.globalData.userId;
    this.setData({ cid, orderId, currentUserId: userId || null });

    if (orderId) {
      wx.setNavigationBarTitle({ title: `订单 ${orderId}` });
    }
    this.loadMessages();
  },

  onPullDownRefresh() {
    this.loadMessages(() => wx.stopPullDownRefresh());
  },

  onInput(e) {
    this.setData({ draft: e.detail.value });
  },

  loadMessages(done) {
    const { cid } = this.data;
    if (!cid) return;

    wx.request({
      url: buildUrl(`/api/messages/${cid}`),
      method: 'GET',
      data: { page: 1, size: 50 },
      success: (res) => {
        const data = res.data || {};
        const list = data.data || data || [];
        this.setData({ messages: list });
        this.scrollToBottom();
      },
      complete: () => {
        if (typeof done === 'function') done();
      }
    });
  },

  scrollToBottom() {
    // 使用 pageScrollTo 让页面滚到底部
    wx.pageScrollTo({ scrollTop: 999999, duration: 0 });
  },

  send() {
    const content = (this.data.draft || '').trim();
    if (!content) return;

    const app = getApp();
    const userId = app.globalData && app.globalData.userId;
    if (!userId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      wx.reLaunch({ url: '/pages/login/login' });
      return;
    }

    const cid = this.data.cid;
    this.setData({ draft: '' });

    wx.request({
      url: buildUrl(`/api/messages/${cid}/send`),
      method: 'POST',
      data: { sender_id: userId, content },
      header: { 'Content-Type': 'application/json' },
      success: () => {
        this.loadMessages();
      },
      fail: () => {
        wx.showToast({ title: '发送失败', icon: 'none' });
        this.setData({ draft: content });
      }
    });
  }
});
